package com.yuanli.cosmeticmirror.model.impl;

import android.util.Log;

import androidx.lifecycle.LifecycleOwner;

import com.alibaba.fastjson.JSON;
import com.comenjoysoft.baselibrary.listener.CallbackListener;
import com.orhanobut.logger.Logger;
import com.yuanli.cosmeticmirror.bean.LoginBean;
import com.yuanli.cosmeticmirror.model.biz.ILoginBiz;
import com.rxjava.rxlife.BaseScope;
import com.rxjava.rxlife.RxLife;

import rxhttp.wrapper.param.RxHttp;

import static com.yuanli.cosmeticmirror.base.HttpApi.LOGIN;
import static com.yuanli.cosmeticmirror.base.MyApp.TAG;

public class LoginImpl extends BaseScope implements ILoginBiz {
    public LoginImpl(LifecycleOwner owner) {
        super(owner);
    }


    @Override
    public void login(String phone, String password, CallbackListener<LoginBean> listener) {
        Logger.d("userName: " + phone);
        Logger.d("userPassword: " + password);
        RxHttp.postJson(LOGIN)
                .add("User_Phone", phone)
                .add("User_Pwd", password)
                .subscribeOnIo()
                .asString()
                .as(RxLife.asOnMain(this)) //返回String类型
                .subscribe(str -> {          //订阅观察者，
                    Log.d(TAG, " login success json :" + str);
                    LoginBean response = JSON.parseObject(str, LoginBean.class);
                    Log.d(TAG, " login onSuccess: " + response.getAPP_Name());
                    if (response.getUser_ID() > 0) {
                        listener.success(response);
                    } else  {
                        Log.d(TAG, " login success failed: " + response.getUser_ID());
                        listener.failed(null);
                    }
                }, throwable -> {
                    //请求失败
                    Log.d(TAG, " login failed: " + throwable.getMessage());
                    listener.failed(throwable.getMessage());
                });
    }
}
